﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using LY.Common;
using LY.Entity;

namespace QJ.CMS.Areas.Admin.Controllers
{
    public class HelperController : Controller
    {
        //
        // GET: /Helper/

        public ActionResult Index()
        {
            return View();
        }
        public static string TitlePic;//图片原名称
        public static string Pictures;//新创建名称
        public static string fileName;//创建文件夹名称
        public string UploadImg()
        {
            string _filedir = Server.MapPath(@"/FileUpload/");    //文件目录  
            int cout = Request.Files.Count;
            if (cout > 0)
            {
                HttpPostedFileBase hpf = Request.Files[0];
                if (hpf != null)
                {
                    //判断文件大小    
                    int length = hpf.ContentLength;
                    if (length > 2048000)
                    {
                        return "-2";
                    }
                    TitlePic = hpf.FileName;
                    if (!Directory.Exists(_filedir))
                    {
                        Directory.CreateDirectory(_filedir);
                    }
                    hpf.SaveAs(UpLoadFile(hpf.FileName, _filedir));

                    if (TitlePic.LastIndexOf("\\") > -1)
                    {
                        TitlePic = TitlePic.Substring(TitlePic.LastIndexOf("\\") + 1);
                    }

                    string Name =TitlePic+"/"+Pictures+"/"+fileName;

                    return Name;
                }

            }
            return "-3";
        }

        /// <summary>
        /// 变换尺寸保存图片
        /// </summary>
        /// <returns></returns>
        public string UploadImg2()
        {
            string _filedir = Server.MapPath(@"/FileUpload/");    //文件目录  
            int cout = Request.Files.Count;
            if (cout > 0)
            {
                HttpPostedFileBase hpf = Request.Files[0];
                if (hpf != null)
                {
                    //判断文件大小    
                    int length = hpf.ContentLength;
                    if (length > 2048000)
                    {
                        return "-2";
                    }
                    TitlePic = hpf.FileName;
                    if (!Directory.Exists(_filedir))
                    {
                        Directory.CreateDirectory(_filedir);
                    }


                    //string fullpath = UpLoadFile(hpf.FileName, _filedir);

                    string fileNamePath = hpf.FileName;
                    string toFilePath = _filedir;
                    string toFileFullPath = "";
                    string remoteUrl = "";
                    //获取要保存的文件信息
                    FileInfo file = new FileInfo(fileNamePath);
                    //获得文件扩展名
                    string fileNameExt = file.Extension;

                    //验证合法的文件
                    if (CheckFileExt(fileNameExt))
                    {
                        //生成将要保存的随机文件名
                        Pictures = GetFileName();
                        //检查保存的路径 是否有/结尾
                        if (toFilePath.EndsWith("\\") == false) toFilePath = toFilePath + "\\";

                        //按日期归类保存 + "-" + DateTime.Now.ToString("dd") + ""
                        fileName = DateTime.Now.ToString("yyyyMMdd");
                        toFilePath += fileName + "\\";

                        //获得要保存的文件路径
                        toFileFullPath = toFilePath + Pictures + fileNameExt;

                        remoteUrl = "/FileUpload/" + fileName + "/" + Pictures + "_small" + fileNameExt;
                        //检查是否有该路径  没有就创建
                        if (!Directory.Exists(toFilePath))
                        {
                            Directory.CreateDirectory(toFilePath);
                        }
                        

                    }
                    else
                    {
                        return "-1";
                    }

                    hpf.SaveAs(toFileFullPath);

                    MemoryStream MemStream = new MemoryStream();
                    System.Drawing.Image imgOutput = System.Drawing.Bitmap.FromFile(toFileFullPath);
                    System.Drawing.Image imgOutput2 = imgOutput.GetThumbnailImage(298, 349, null, IntPtr.Zero);
                    imgOutput2.Save(System.Web.HttpContext.Current.Server.MapPath(remoteUrl), System.Drawing.Imaging.ImageFormat.Jpeg);

                    if (TitlePic.LastIndexOf("\\") > -1)
                    {
                        TitlePic = TitlePic.Substring(TitlePic.LastIndexOf("\\") + 1);
                    }

                    string Name = TitlePic + "/" + Pictures + fileNameExt + "/" + fileName;

                    return Name;
                }

            }
            return "-3";
        }

        [HttpPost]
        public JsonResult UploadFile()
        {
            var siteconfig = (S_Siteconfig)SerializationHelper.Load(typeof(S_Siteconfig), Utility.GetXmlMapPath("Configpath")); 
       
            JsonImgMsg jsonImgMsg = new JsonImgMsg();
            string text = siteconfig.Filepath;
            string text2 = base.HttpContext.Server.MapPath("~/") + text;
            if (!Directory.Exists(text2))
            {
                Directory.CreateDirectory(text2);
            }
            try
            {
                for (int i = 0; i < base.Request.Files.Count; i++)
                {
                    HttpPostedFileBase httpPostedFileBase = base.Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        HttpPostedFileBase httpPostedFileBase2 = base.Request.Files[i];
                        if (httpPostedFileBase2 != null)
                        {
                            string text3 = DateTime.Now.ToString("yyyyMMddhhmmss") + httpPostedFileBase2.FileName.Substring(httpPostedFileBase2.FileName.LastIndexOf('.'));
                            httpPostedFileBase.SaveAs(text2 + text3);
                            jsonImgMsg.name = text3;
                            jsonImgMsg.path = text2;
                            jsonImgMsg.thumb = text + text3;
                            jsonImgMsg.size = httpPostedFileBase2.ContentLength;
                            jsonImgMsg.ext = httpPostedFileBase2.FileName.Substring(httpPostedFileBase2.FileName.LastIndexOf('.') + 1);
                        }
                    }
                }
            }
            catch (Exception)
            {
                jsonImgMsg.status = 0;
                jsonImgMsg.msg = "上传过程中发生意外错误！";
                return base.Json(jsonImgMsg);
            }
            jsonImgMsg.imgtype = 2;
            jsonImgMsg.status = 1;
            jsonImgMsg.msg = "上传文件成功！";
            return Json(jsonImgMsg);
        }
        /// <summary>
        /// 上传文件 方法
        /// </summary>
        /// <param name="fileNamePath"></param>
        /// <param name="toFilePath"></param>
        /// <returns>返回上传处理结果   格式说明： 0|file.jpg|msg   成功状态|文件名|消息    </returns>
        public string UpLoadFile(string fileNamePath, string toFilePath)
        {
            try
            {
                //获取要保存的文件信息
                FileInfo file = new FileInfo(fileNamePath);
                //获得文件扩展名
                string fileNameExt = file.Extension;

                //验证合法的文件
                if (CheckFileExt(fileNameExt))
                {
                    //生成将要保存的随机文件名
                    Pictures = GetFileName() + fileNameExt;
                    //检查保存的路径 是否有/结尾
                    if (toFilePath.EndsWith("\\") == false) toFilePath = toFilePath + "\\";

                    //按日期归类保存 + "-" + DateTime.Now.ToString("dd") + ""
                    fileName = DateTime.Now.ToString("yyyyMMdd");
                    toFilePath += fileName + "\\";

                    //获得要保存的文件路径
                    string toFileFullPath = toFilePath + Pictures;
                    //检查是否有该路径  没有就创建
                    if (!Directory.Exists(toFilePath))
                    {
                        Directory.CreateDirectory(toFilePath);
                    }
                    return toFileFullPath;

                }
                else
                {
                    return "-1";
                }
            }
            catch (Exception e)
            {
                return "0|errorfile|" + "文件上传失败,错误原因：" + e.Message;
            }
        }

        /// <summary>
        /// 检查是否为合法的上传文件
        /// </summary>
        /// <param name="_fileExt"></param>
        /// <returns></returns>
        private bool CheckFileExt(string _fileExt)
        {
            string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".png" };
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i] == _fileExt) { return true; }
            }
            return false;

        }

        public static string GetFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(Guid.NewGuid());
            //serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            //serial.Append(rd.Next(0, 999999).ToString());
            return serial.ToString();

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class JsonImgMsg
    {
        public int status { get; set; }
        public string msg { get; set; }
        public string name { get; set; }
        public string path { get; set; }
        public string thumb { get; set; }
        public int size { get; set; }
        public string ext { get; set; }
        public int imgtype { get; set; }
    }
}
